package com.zhaopin.utils;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.*;

public class FileUtil {

    public static String readFile(String Path) {
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    public static String readFile(File file) {
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    public static String readFile(String path, int start, int end) {
        File file = new File(path);
        if (!file.exists())
            return "file not exist";

        if (null == file.listFiles())
            return "file not exist";

        String fileName = null;
        for (File f : file.listFiles()) {
            if (f.getName().startsWith("java-s-aggregator"))
                fileName = f.getAbsolutePath();
        }

        if (null == fileName)
            return "file not exist";

        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(fileName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            int index = 0;
            while ((tempString = reader.readLine()) != null) {
                if (index >= start && index <= end)
                    laststr += tempString;
                index++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    public static List<String> readFileList(String filePath) {
        List<String> result = new ArrayList<String>();
        File f = new File(filePath);
        if (!f.exists()) {
            return result;
        }
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(
                    new FileInputStream(f), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.length() > 0) {
                    result.add(line);
                }
            }
            isr.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != isr) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static List<String> readFileList(File f) {
        List<String> result = new ArrayList<String>();
        if (!f.exists()) {
            return result;
        }
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(
                    new FileInputStream(f), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.length() > 0) {
                    result.add(line);
                }
            }
            isr.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != isr) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static void writeFile(String fileName, List<String> list) {
        if (list.size() == 0)
            return;

        File file = new File(fileName);
        file.delete();
        try {
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            for (String line : list) {
                output.write(line + "\r\n");
            }
            output.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> getAllFilePath(String folder, String rootPath) {
        Map<String, String> res = new HashMap<>();

        File file = new File(folder);
        if (!file.exists())
            return res;

        if (null == rootPath)
            rootPath = PathUtil.formatPath(file.getAbsolutePath());

        getAllFilePath(file, res, rootPath);

        return res;
    }

    private static void getAllFilePath(File file, Map<String, String> res, String rootPath) {
        if (!file.isDirectory()) {
            if (rootPath.startsWith("/"))
                rootPath = rootPath.substring(1);

            String path = PathUtil.formatPath(file.getAbsolutePath()).replace(rootPath + "/", "");
            if (path.startsWith("/"))
                path = path.substring(1);

            res.put(file.getName(), path);
        } else {
            if (null == file.listFiles())
                return;

            for (File f : file.listFiles())
                getAllFilePath(f, res, rootPath);
        }
    }

    public static List<String> listFileName(File file, boolean replace) {
        List<String> res = new LinkedList<>();

        if (null == file || !file.exists() || file.listFiles() == null)
            return res;

        for (File f : file.listFiles()) {
            String name = f.getName();
            if (replace) {
                name = name.split("\\.")[0];
            }
            res.add(name);
        }


        return res;
    }

    public static Map<String, Map<String, Long>> getExpAllFileLastModify(String folder) {
        Map<String, Map<String, Long>> res = new HashMap<>();

        File file = new File(folder);
        if (null == file.listFiles())
            return res;

        for (File f : file.listFiles()) {
            Map<String, Long> map = new HashMap<>();
            getAllFileLastModify(f, map, false);

            if (map.size() > 0)
                res.put(f.getName(), map);
        }

        return res;
    }

    public static Map<String, Long> getAllFileLastModify(String folder) {
        Map<String, Long> res = new HashMap<>();

        File file = new File(folder);

        getAllFileLastModify(file, res, false);

        return res;
    }

    public static Map<String, Long> getAllFileLastModifyOnlyExceptVersion(String folder) {
        Map<String, Long> res = new HashMap<>();

        File file = new File(folder);

        getAllFileLastModify(file, res, true);

        return res;
    }

    public static boolean exist(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    public static void getAllFileLastModify(File file, Map<String, Long> res, boolean version) {
        if (!file.exists())
            return;

        if (file.isDirectory()) {
            if (null == file.listFiles())
                return;

            for (File f : file.listFiles()) {
                getAllFileLastModify(f, res, version);
            }
        } else {
            String name = file.getName();
            if (version) {
                if (name.equals("version") || name.contains("DS_"))
                    return;
            } else {
                if (!name.endsWith("groovy") && !name.endsWith("json") && !name.endsWith("tsv"))
                    return;
            }

            res.put(file.getPath(), file.lastModified());
        }
    }

    public static void createFolder(String folder) {
        File file = new File(folder);
        if (file.exists())
            return;

        file.mkdirs();
    }

    public static void deleteFolder(String folder) throws IOException {
        File file = new File(folder);
        if (!file.exists())
            return;

        FileUtils.deleteDirectory(file);
    }

    public static void delete(String path) {
        File file = new File(path);
        if (!file.exists())
            return;

        file.delete();
    }

    public static void copyDirectory(String path, String toPath) throws IOException {
        File file = new File(path);
        if (!file.exists())
            return;

        deleteFolder(toPath);
        FileUtils.copyDirectory(new File(path), new File(toPath));
    }

    public static List<File> getFiles(String path) {
        List<File> res = new LinkedList<>();
        File file = new File(path);
        if (!file.exists())
            return res;

        File[] files = file.listFiles();
        if (null == files)
            return res;

        res.addAll(Arrays.asList(files));

        return res;
    }

    public static List<File> getAllFiles(String path) {
        List<File> list = new LinkedList<>();
        File root = new File(path);
        getAllFiles(root, list);
        return list;
    }

    public static void getAllFiles(File file, List<File> list) {
        if (!file.exists())
            return;

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null == files)
                return;

            for (File f : files) {
                getAllFiles(f, list);
            }
        } else {
            if (file.getName().contains("DS_Store"))
                return;

            list.add(file);
        }
    }
}
